<template>

	<view>

		<view class="pay-mode">
			<view class="pay-title">
				<text>支付方式</text>
			</view>

			<view class="mode-item">
				<view class="mode-left">
					<view>
						<van-icon name="vip-card-o" size="60rpx" color="royalblue" />
					</view>
					<view class="left-text">
						<text>影城会员卡</text>
						<text style="color:royalblue">即开即用，会员购票享优惠！！</text>
					</view>
				</view>
				<view class="select-icon" @click="showSelectCard">
					<view style="font-size: 26rpx;color: #999;">
						<text style="color: royalblue;">{{cardList.length?cardText:'立即开卡'}}</text>
						<van-icon name="arrow" />
					</view>
				</view>
			</view>
			<view class="mode-item" @click="wxClick">
				<view class="mode-left">
					<view>
						<van-icon name="wechat-pay" size="60rpx" color=" #00e600" />
					</view>
					<view class="left-text">
						<text>微信支付</text>
						<text>应付款￥{{amount}}</text>
					</view>
				</view>
				<view class="select-icon">
					<van-icon name="checked" size="50rpx" :color="payMode=='wx'?'royalblue':'#999'" />
				</view>
			</view>
			<view class="mode-item">
				<view class="mode-left">
					<view>
						<van-icon name="coupon-o" size="60rpx" color="#DD524D" />
					</view>
					<view class="left-text">
						<text>优惠券</text>
						<text style="color:#DD524D;">使用优惠券购买影票更优惠</text>
					</view>
				</view>
				<view class="select-icon" @click="selectCoupon">
					<view style="font-size: 26rpx;color: #DD524D;">
						<text>{{payMode==='coupons'?`已选${selectedCoupons.length}张`:'选择优惠券'}}</text>
						<van-icon name="arrow" />
					</view>
				</view>
			</view>


		</view>
		<van-popup :show="showCard" position="bottom" @touchmove.stop.prevent="moveStop"
			@click-overlay="showCard=false">
			<view class="select-card-list" v-for="item in cardList" :key="item.cardCode">
				<view class="select-card" @click="slectedCard(item.cardCode,item.balance,item.policyId)">
					<text>{{item.memberPolicy}}</text>
					<text>卡号：{{item.cardCode}}</text>
					<!-- <text>余额：{{item.balance}}元</text> -->
				</view>
			</view>
		</van-popup>
		<van-popup :show="showPassword" @click-overlay="showPassword=false">
			<view class="input-password">
				<van-field label="密码" password type="number" :model:value="cardPayParams.password" @change="change"
					placeholder="请输入密码" :border="false" />
				<van-button round type="info" :disabled="!canCardPay" @click="getCard"
					custom-style="margin-top:30rpx;width:60vw;height:60rpx;">
					确定</van-button>
			</view>
		</van-popup>
		<!-- showCoupon -->
		<van-popup :show="showCoupon" position="bottom" @click-overlay="showCoupon=false" custom-style="height: 50vh;"
			@touchmove.stop.prevent="moveStop">
			<view class="coupon-popup">
				<view class="title">优惠券</view>
				<view class="coupon-list">
					<view
						:class="selectedCoupons.indexOf(item.couponCheckCode)==-1?'list-item':'list-item list-item-select'"
						style="height: 150rpx;" v-for="(item,index) in couponList" :key="index"
						@click="selectCouponFn(item.couponCheckCode,1)">
						<text>{{item.policyName}}</text>
						<text>有效期至:</text>
						<text>{{item.useEndDate}}</text>
					</view>
				</view>

				<view style="position: fixed;bottom: 20rpx;width: 90%;">
					<van-button round @click='couponPay' color="linear-gradient(to right, #99d6ff, #008ae6)"
						size="large">
						优惠券支付
					</van-button>
				</view>
			</view>
		</van-popup>
		<van-popup :show="showGiveCoupon" position="bottom" @click-overlay="showGiveCoupon=false"
			custom-style="height: 50vh;" @touchmove.stop.prevent="moveStop">
			<view class="coupon-popup">
				<view class="title">会员兑换券</view>
				<view class="coupon-list">
					<view :class="selectedCoupons.indexOf(item.checkCode)==-1?'list-item':'list-item list-item-select'"
						v-for="(item,index) in giveCouponList" :key="index"
						@click="selectCouponFn(item.checkCode,2,item.hallCode)">
						<text>{{item.giveCouponPolicyName}}</text>
						<text style="font-size: 24rpx;" v-if="item.hallCode">可用：{{getScreenName(item.hallCode)}}</text>
						<text>{{item.realEndDate}}前</text>
					</view>
				</view>
				<view style="position: fixed;bottom: 20rpx;width: 90%;">
					<van-button round @click='giveCouponPay' color="linear-gradient(to right, #99d6ff, #008ae6)"
						size="large">兑换券支付
					</van-button>
				</view>
			</view>
		</van-popup>
		<view class="pay">
			<view class="pay-money">
				<text>应付:</text>
				<!-- <text class="total-price">￥ {{payMode==='card'?cardPayMoney:amount}}</text> -->
				<text class="total-price">￥ {{amount}}</text>
				<!-- 		<text
					style="font-size: 20rpx;line-height: 60rpx;">(含服务费{{payMode==='card'?cardServiceFee:channelFee}}元)</text> -->
			</view>
			<view class="">
				<van-button round @click='pay' :disabled="!canCardPay"
					color="linear-gradient(to right, #99d6ff, #008ae6)" size="large">立即支付
				</van-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		wxPay,
		getCardList,
		queryCouponList,
		queryGiveCouponList,
		getMemberPrice,
		goodsMeberPay,
		goodsOrder,
		payByCoupons,
		payByGiveCoupons,
		getCardInfo
	} from '../../common/http/api.js'
	import {
		checkPhone
	} from '../../common/formCheck.js'
	export default {
		data() {
			return {
				amount: 0,
				orderParams: {
					orderPhone: '',
					openId: '',
					listGoodsInfo: []
				},
				payParams: {
					orderNo: '',
					openId: '',
					orderPhone: '',
				},
				orderData: {},
				wxPayMoney: '',
				balance: "",
				cardPayMoney: '',
				cardServiceFee: 0,
				cardList: [],
				couponList: [],
				giveCouponList: [],
				isWxPay: true,
				cardText: '请选择会员卡',
				showCard: false,
				showCoupon: false,
				showGiveCoupon: false,
				showPassword: false,
				payMode: 'wx',
				getMemberPriceParams: {
					orderNo: '',
					cardCode: ''
				},
				cardPayParams: {
					openId: uni.getStorageSync("openId"),
					orderNo: '',
					password: "",
					orderPhone: '',
					cardCode: "",
				},
				couponPayForm: {
					openId: '',
					coupons: "",
					orderNo: '',
					lowestPrice: '',
					orderTotal: ''
				},
				isPay: false,
				selectedCoupons: [],
				getCardParams: {
					cardCode: '',
					password: ''
				},
				canCardPay: true,
				screenCode: '',
				channelFee: 0,
				cardPolicyId: ''
			};
		},
		methods: {
			moveStop() {},
			change(e) {
				this.cardPayParams.password = e.detail
				this.getCardParams.password = e.detail
			},
			inputPassword(e) {
				this.cardPayParams.password = e.detail
			},
			wxClick() {
				this.selectedCoupons = []
				this.payMode = 'wx'
				this.isWxPay = false
				this.cardServiceFee = 0
			},
			pay() {
				if (!this.$store.state.userPhone) {
					uni.navigateTo({
						url: "../../pages/getPhone/getPhone"
					})
					return
				}
				
				const _params = this.orderParams;

				_params.listGoodsInfo.map(item => {
					item.retailPrice = parseFloat(item.retailPrice * item.count).toFixed(2)
				})

				goodsOrder(_params).then(result => {
					if (result.code == "SUCCESS") {
						this.payParams.orderNo = result.data.orderNo
						this.cardPayParams.orderNo = result.data.orderNo
						if (this.payMode === 'wx') this.wxPay()
						else if (this.payMode === 'card') this.showPassword = true
						else {
							uni.showToast({
								title: "暂未开放",
								icon: "none"
							})
						}
					}
				})
				// else if (this.payMode === 'card') this.showPassword = true
				// else if (this.payMode == 'coupon') this.couponPay()
				// else if (this.payMode == 'giveCoupon') this.giveCouponPay()
			},
			//拉起微信支付
			wxPay() {
				this.canCardPay = false
				wxPay(this.payParams).then(res => {
					const {
						data,
						code
					} = res
					if (code === "SUCCESS") {
						uni.requestPayment({
							timeStamp: data.timeStamp,
							nonceStr: data.nonceStr,
							package: data.package,
							signType: data.signType,
							paySign: data.paySign,
							appId: data.appId,
							success: res => {
								if (res.errMsg === "requestPayment:ok") {
									this.$store.commit('clearCart')
									uni.redirectTo({
										url: '../goodsOrderList/goodsOrderList'
									})
								}

							},
							fail: () => {
								this.canCardPay = true
							}

						})
					}
				})
			},
			//查询会员卡
			queryCard() {
				getCardList(uni.getStorageSync("openId")).then(res => {
					const {
						code,
						data
					} = res
					if (code === "000") {
						this.cardList = data
					}
				})
			},
			getCard() {
				this.canCardPay = false;
				//获取会员卡信息
				getCardInfo(this.getCardParams).then(res => {
					const {
						data,
						code,
						msg
					} = res
					if (code === '000') {
						this.balance = data.balance
						if (parseFloat(this.balance) < parseFloat(this.cardPayMoney)) {
							uni.showModal({
								confirmText: '立即充值',
								title: '会员卡余额不足，请充值',
								success: showResult => {
									if (showResult.confirm) {
										uni.navigateTo({
											url: "../cardPage/cardPage?cardCode=" + this
												.getCardParams.cardCode + '&password=' +
												this.getCardParams.password
										})
									}
								}
							})
							setTimeout(() => {
								this.canCardPay = true;
							}, 2000)
							this.cardList.find((item) => {
								if (item.cardCode == this.getCardParams.cardCode) {
									item.balance = this.balance
								}
							})
						} else {
							this.cardPay();
						}
					} else {
						uni.showToast({
							title: msg,
							icon: "none"
						})
						this.canCardPay = true;
					}

				})
			},
			//查询优惠券
			queryCoupon() {
				queryCouponList(uni.getStorageSync("openId")).then(res => {
					const {
						code,
						obj
					} = res
					if (code === '000') {
						obj.map(item => {
							if (item.flag === '1') {
								this.couponList.push(item);
							}
						})

					}
				})

			},
			queryGiveCoupon(cardCode) {
				queryGiveCouponList({
					cardCode
				}).then(res => {
					const {
						code,
						obj
					} = res
					if (code === '000') {
						this.giveCouponList = obj
						if (this.giveCouponList.length) {
							uni.showModal({
								title: "请选择会员卡支付方式",
								cancelText: '会员余额',
								confirmText: '兑换券',
								success: res => {
									if (res.confirm) {
										this.payMode = 'giveCoupon'
										this.couponPayForm.orderNo = this.orderNo
										this.couponModal(2)
										this.cardServiceFee = 0
									} else {
										this.payMode = 'card'
										this.showPassword = true
									}
								}
							})
						}
					}
				})
			},
			//展示选择优惠券
			selectCoupon() {
				this.couponPayForm.orderNo = this.orderNo
				this.payMode = 'coupons'
				this.couponModal(1)
			},
			//展示选择会员卡
			showSelectCard() {
				if (this.cardList.length) {
					this.showCard = true
				} else {
					uni.redirectTo({
						url: "../../pages/openCard/openCardList"
					})
				}
			},
			//获取会员价
			slectedCard(cardCode, balance, cardPolicyId) {
				this.cardServiceFee = 0
				this.balance = balance
				this.cardPolicyId = cardPolicyId
				this.getCardParams.cardCode = cardCode
				this.getMemberPriceParams.cardCode = cardCode
				this.cardPayParams.cardCode = cardCode
				this.showCard = false
				this.isWxPay = false
				this.payMode = 'card'
				const code = cardCode.slice(-3)
				this.cardText = `已选择***${code}`
				this.queryGiveCoupon(cardCode);

			},
			couponModal(type) {
				uni.showModal({
					title: "温馨提示",
					content: '支付后若退票无法退换券，请您知晓！',
					success: res => {
						if (res.confirm) {
							if (type == 1) this.showCoupon = true;
							else this.showGiveCoupon = true
						}
					}
				})
			},
			cardPay() {
				if (!this.cardPayParams.orderNo) {
					uni.showToast({
						title: "网络异常请重试",
						icon: "none"
					})
					this.showPassword = false
					return
				}
				goodsMeberPay(this.cardPayParams).then(res => {
					const {
						code,
						msg
					} = res;
					if (code === "SUCCESS") {
						this.cardPayParams = {}
						this.isPay = true
						uni.showToast({
							title: '支付成功',
							icon: "none",
							duration: 1500
						})
						this.$store.commit('clearCart')
						setTimeout(() => {

							uni.redirectTo({
								url: '../goodsOrderList/goodsOrderList'
							})
						}, 1500)
					} else {
						uni.showToast({
							title: msg,
							icon: "none"
						})

						this.canCardPay = true;
					}
				})
			},
			selectCouponFn(couponId, type, hallCode) {
				if (hallCode && type == '2') {
					if (hallCode.indexOf(this.screenCode) == -1) {
						uni.showToast({
							title: "当前影厅不可使用该兑换券",
							icon: "none"
						})
						return
					}
				}
				if (this.selectedCoupons.indexOf(couponId) == -1) {
					if (this.releaseSeatParams.Count == this.selectedCoupons.length) return
					this.selectedCoupons.push(couponId)
				} else {
					const index = this.selectedCoupons.indexOf(couponId)
					this.selectedCoupons.splice(index, 1)
				}
				if (this.selectedCoupons.length === 1) this.couponPayForm.coupons = this.selectedCoupons.toString();
				else if (this.selectedCoupons.length > 1) this.couponPayForm.coupons = this.selectedCoupons.join(",");
				if (type == '2') this.cardText = `已选${this.selectedCoupons.length}张兑换券`
			},
			couponPay() {
				if (this.selectedCoupons.length < this.$store.state.sessionSeatList.length) {
					uni.showToast({
						title: "优惠券不足",
						icon: "none"
					})
					return
				}
				payByCoupons(this.couponPayForm).then(res => {
					const {
						code,
						msg
					} = res;
					if (code === "SUCCESS") {
						uni.showToast({
							title: msg,
							icon: "none",
							duration: 1500
						})
						this.isPay = true
						setTimeout(() => {
							uni.redirectTo({
								url: '../../pages/orderPage/orderPage?orderCode=' + this
									.orderCode + '&statusText=待取票'
							})
						}, 1500);
					} else {
						uni.showToast({
							title: msg,
							icon: "none",
							duration: 1500
						})
					}
				})
			},
			giveCouponPay() {
				if (this.selectedCoupons.length < this.$store.state.sessionSeatList.length) {
					uni.showToast({
						title: "会员兑换券不足",
						icon: "none"
					})
					return
				}

				payByGiveCoupons(this.couponPayForm).then(res => {
					const {
						code,
						msg
					} = res;
					if (code === "SUCCESS") {
						uni.showToast({
							title: msg,
							icon: "none",
							duration: 1500
						})
						this.isPay = true
						setTimeout(() => {
							uni.redirectTo({
								url: '../../pages/orderPage/orderPage?orderCode=' + this
									.orderCode + '&statusText=待取票'
							})
						}, 1500);
					} else {
						uni.showToast({
							title: msg,
							icon: "none",
							duration: 1500
						})
					}
				})
			}
		},
		created() {
			this.queryCard()
			this.queryCoupon()
			this.payParams.orderPhone = this.$store.state.userPhone
			this.cardPayParams.orderPhone = this.$store.state.userPhone
			this.orderParams.orderPhone = this.$store.state.userPhone
			this.payParams.openId = uni.getStorageSync("openId")
			this.orderParams.openId = uni.getStorageSync("openId")
			this.orderParams.listGoodsInfo = this.$store.state.goodsList
			this.orderParams.listGoodsInfo.map(item => {
				this.amount += parseFloat((item.retailPrice * item.count).toFixed(2))
			})
		},
		watch: {
			selectedCoupons(n) {
				if (n.length != 0) {
					this.isWxPay = false
				}
			},
			isRelease(n) {
				if (n) {
					releaseSeat(this.releaseSeatParams)
				}
			},
			payMode(n) {
				this.selectedCoupons = []
				this.amount = 0
				if (n == 'wx') {
					this.orderParams.listGoodsInfo.map(item => {
						item.retailPrice = item.sourcePrice
						this.amount += parseFloat((item.retailPrice * item.count).toFixed(2))
					})
					this.$emit('changePolicy', '')
				} else if (n == 'card') {
					this.$emit('changePolicy', this.cardPolicyId)
					const list = []
					this.orderParams.listGoodsInfo.map(item => {
						if (item.memberPrice) {
							item.memberPrice.find(price => {
								if (price.policyId == this.cardPolicyId) {
									if (price.memberPrice) {
										const newItem = JSON.parse(JSON.stringify(item))
										newItem.retailPrice = price.memberPrice
										item.retailPrice = price.memberPrice
										list.push(newItem)
									} else if (price.goodDiscount) {
										const newItem = JSON.parse(JSON.stringify(item))
										newItem.retailPrice = (price.goodDiscount * item.retailPrice)
											.toFixed(
												2)
										item.retailPrice = (price.goodDiscount * item.retailPrice).toFixed(
											2)
										list.push(newItem)
									}
								}
							})
						}
						this.amount += parseFloat((item.retailPrice * item.count).toFixed(2))
					})
					this.orderParams.listGoodsInfo = list
				}
			},
			"$store.state.userPhone"(){
				this.payParams.orderPhone = this.$store.state.userPhone
				this.cardPayParams.orderPhone = this.$store.state.userPhone
				this.orderParams.orderPhone = this.$store.state.userPhone
			}
		},
	}
</script>

<style lang="scss">
	@import url(../../common/css/couponStyle.css);

	::v-deep .van-checkbox {
		margin-top: 15rpx !important;
	}

	.custom-class {
		margin-top: 15rpx !important;
	}

	.input-password {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 80vw;
		height: 200rpx;
		padding: 30rpx;
	}

	.phone {
		display: flex;
		padding: 20rpx 4vw;
		justify-content: space-between;
		align-items: center;
		background-color: #fff;
		margin-top: 15rpx;
		font-size: 26rpx;

		input {
			width: 180rpx;
		}
	}

	.pay-mode {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #fff;
		margin-top: 15rpx;

		.pay-title {
			font-size: 26rpx;
			width: 92vw;
			border-bottom: 1px solid #f0f0f5;
			line-height: 80rpx;
		}

		.mode-item {
			display: flex;
			justify-content: space-between;
			height: 100rpx;
			padding: 15rpx 0;
			width: 92vw;

			.mode-left {
				display: flex;
				align-items: center;


				.left-text {
					display: flex;
					flex-direction: column;
					font-size: 32rpx;
					margin-left: 20rpx;

					text:last-child {
						font-size: 22rpx;
						color: #999;
					}
				}
			}

			.select-icon {
				height: 100%;
				display: flex;
				align-items: center;
			}
		}
	}

	.select-card-list {
		width: 100vw;
		height: 10vh;
		padding-top: 15rpx;

		.select-card {
			display: flex;
			background-color: #fff;
			width: 90vw;
			margin: 0rpx auto 10rpx auto;
			box-shadow: 4px 4px 4px #f0f0f5;
			justify-content: space-between;
			color: #999;
			padding: 30rpx 20rpx;
			border-radius: 10rpx;
			font-size: 30rpx;
		}

	}

	.pay {
		position: fixed;
		bottom: 0;
		width: 92vw;
		padding: 15rpx 4vw 30rpx 4vw;
		background-color: #fff;

		.pay-money {
			font-size: 28rpx;
			display: flex;
			align-items: flex-end;

			text {
				line-height: 70rpx;
			}

			.total-price {
				font-size: 32rpx;
				color: #cc4444;
				font-weight: bold;
			}

			.server-fee {
				margin-left: 5rpx;
				font-size: 22rpx;
				color: #cc4444;
			}
		}
	}

	.coupon-popup {
		padding: 30rpx 50rpx;
		font-size: 28rpx;
		color: #999;

		.title {
			text-align: center;
			color: #333;
			margin-bottom: 20rpx;
		}

		// .coupon-item {
		// 	margin-top: 30rpx;

		// 	.date {
		// 		margin-left: 20rpx;
		// 	}
		// }
		.coupon-list {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.list-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				color: royalblue;
				width: 45%;
				height: 170rpx;
				font-size: 24rpx;
				text-align: center;
				margin-bottom: 15rpx;
				border-radius: 10rpx;
				background-size: 100% 100%;

				text {
					margin: 5rpx 0;
				}

				&:not(:nth-child(3n)) {
					margin-right: calc((100vw - 100rpx - 600rpx)/3)
				}
			}

			.list-item-select {
				color: #cc4444;
			}

		}

	}
</style>